<template>
	<view>
		<view style="width: 100%; height: 60rpx;margin-bottom: 20rpx; background-color: pink;" v-for="(item,index) in soundPathList"
		 :key='index' @tap='playVoice(item)'>{{item.duration}}</view>
		<view @touchstart='startRecord()' @touchend='endRecord()' class="icon">
			<u-icon name="mic"></u-icon>
		</view>
	</view>
</template>

<script>
	/* 获取录音的时长有两种方案,分别有各自的使用场景:
	 * 1.根据结束时间 - 开始时间进行计算
	 *		通常使用在 需要上传音频时使用
	 * 2.利用myAudio.onCanplay()方法获取
	 * 		通常使用在 需要知道接口中返回的音频的时长
	 */
	let recorderManager = uni.getRecorderManager()
	let myAudio = null
	let startTime = 0
	let endTime = 0
	export default {
		data() {
			return {
				soundPathList: []
			}
		},
		onLoad() {
			const _this = this
			myAudio = uni.createInnerAudioContext()
			this.mockGetAudioFile()
			recorderManager.onStop(res => {
				_this.soundPathList.push({
					path: res.tempFilePath,
					duration: (Math.abs(endTime - startTime) / 1000).toFixed(2) + '"'
				})
			})
		},
		beforeDestroy() {
			myAudio.destroy()
		},
		methods: {
			mockGetAudioFile() {
				this.soundPathList = []
				const _this = this
				const srcList = ['../../../../static/audioFile.m4a', '../../../../static/audioFile2.m4a']
				for (let el of srcList) { //let ... of ... 保证按照顺序执行
					const selfAudioContext = uni.createInnerAudioContext()
					selfAudioContext.src = el
					selfAudioContext.onCanplay(() => {
						selfAudioContext.duration
						_this.$nextTick(() => {
							_this.soundPathList.push({
								path: el,
								duration: selfAudioContext.duration.toFixed(2) + '"'
							})
							selfAudioContext.destroy()
						})
					})
				}
			},
			startRecord() {
				startTime = new Date().getTime()
				recorderManager.start({
					duration: '20000', // 默认1分钟:60000ms 单位ms
					numberOfChannels: 1,
					format: 'mp3' // 音频格式,
				})
			},
			endRecord() {
				endTime = new Date().getTime()
				if (endTime - startTime < 1000) {
					uni.showToast({
						title: '录音时长不得小于1s',
						icon: 'none'
					})
				} else {
					recorderManager.stop()
				}
			},
			playVoice(item) {
				if (item.path) {
					myAudio.src = item.path
					myAudio.play()
				} else {
					uni.showToast({
						title: '文件路径错误,请查看文件路径是否正常',
						icon: 'none'
					})
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	.icon {
		background-color: rgba($color: #333, $alpha: .6);
		width: 200rpx;
		height: 200rpx;
		text-align: center;
		line-height: 200rpx;
		border-radius: 50%;
		font-size: 100rpx;
		color: pink;
		position: fixed;
		bottom: 80rpx;
		left: 50%;
		transform: translate(-50%);

		&:active {
			opacity: .7;
		}
	}
</style>
